package com.example.web.servlet;

import com.example.dao.UserDao;
import com.example.domain.User;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/loginServlet")
public class loginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.设置编码
        request.setCharacterEncoding("utf-8");
        //2.获取请求参数
//        String username = request.getParameter("username");
//        String password = request.getParameter("password");

        //3.封装参数
//        User user = new User();
//        user.setPassword(password);
//        user.setUsername(username);
        //2.获取请求参数
        Map<String, String[]> parameterMap = request.getParameterMap();
        //3.封装参数
        User user = new User();//JavaBean
        try {
            BeanUtils.populate(user,parameterMap);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        //4.调用Userdao 方法
        UserDao userDao = new UserDao();
        User login = userDao.login(user);
        if(login == null){
            request.getRequestDispatcher("/failServlet").forward(request,response);
        }
        else {
            request.setAttribute("user",login);
            request.getRequestDispatcher("/successServlet").forward(request,response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
